import { MicroAppContext, useRouter } from "..";
import React, { useEffect } from "react";
import { History } from "history";
// import { debug } from "../utils/log";

const useActiveEntry = () => {
  const { modules = [] } = React.useContext(MicroAppContext);
  const { history, pathname } = useRouter();
  const { routes, routeMap, moduleMap, basename } = React.useContext(MicroAppContext);
  const [route, setRoute] = React.useState<any>({});

  const activeModules = modules.filter((v) => v.name);
  const findActiveEntry = (
    routeMap: any,
    pathname: string,
    basename: string
  ): any => {
    if (routeMap[pathname]) {
      return routeMap[pathname];
    }

    for (let key in moduleMap) {
      const item = moduleMap[key];
      const activeModule = item.activeRule();
      if (activeModule) {
        const findActiveModule = activeModules.find(v => v.name === item.activeModule);
        if (findActiveModule) {
          return {
            MicroApp: findActiveModule.MicroApp,
            ...item,
          };
        }
        console.log('itemitemitemitem', item)

      }

      // const item = routeMap[path];
      // const findActiveModule = activeModules.find(({ activeRule }) =>
      //   activeRule(item, basename)
      // );
      // if (findActiveModule) {
      //   return {
      //     MicroApp: findActiveModule.MicroApp,
      //     ...item,
      //   };
      // }
    }

  };
  const matchActiveApp = () => {

    // debug('matchActiveApp')
    console.time("matchActiveApp");
    let item = findActiveEntry(
      routeMap,
      history.location.pathname,
      basename as string
    );
    // debugger
    if (!item) {
      item = {
        name: "404",
        title: "404",
        entry: "/pages/404.js",
      };
    }

    console.timeEnd("matchActiveApp");

    setRoute({ ...item });
  };
  React.useEffect(() => {
    const unListen = history.listen(() => {
      matchActiveApp();
    });
    return () => {
      unListen();
    };
  }, []);
  useEffect(() => {
    matchActiveApp();

  }, [routes]);

  return {
    route,
  };
};
export default useActiveEntry;
